package br.com.merks.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.view.Results;
import br.com.merks.controller.component.SecurityModule;
import br.com.merks.model.User;
import br.com.merks.service.UserService;

@Resource
public class UserController {
	private Validator validator = null;
	private UserService dao = null;
	private Result result = null;
	private SecurityModule loginHandler = null;
	public UserController(UserService dao, Result result, Validator validator, SecurityModule loginHandler) {
			    this.validator = validator;
			    this.dao = dao;
			    this.result = result;
			    this.loginHandler = loginHandler;
	}
	@Get
	@Path(priority = 1, value = "/user/form")
	public void form() {
		
	}
	@Post
	@Path("/user/add")
	public void add(User user) {
		/* Validando a entrada de dados*/
		validator.checking(ValidationRules.isValidUserRegistrationInput(user));
		validator.onErrorUse(Results.page()).of(UserController.class).form();
		/* Executando lógica de negócio */
		dao.registerUser(user);
	}
	@Get
	@Path(priority = 2, value= "/user/{user.id}")
	public User view(User user) {
		return dao.find(user);
	}
	
	@Post
	@Path("/login")
	public void login(User user) {
		this.loginHandler.login(user);
		this.result.use(Results.logic()).forwardTo(IndexController.class).index();
	}
	
	@Path("/logout")
	public void logout() {
		this.loginHandler.logout(null);
		this.result.use(Results.logic()).forwardTo(IndexController.class).index();
	}
	@Path("/user/edit/form")
	public User editForm() {
		return this.loginHandler.getUser();
	}
	@Post
	@Path("/user/edit")
	public void edit(User user) {
		/* Validando a entrada de dados*/
		validator.checking(ValidationRules.isValidUserEditionInput(user));
		validator.onErrorUse(Results.page()).of(UserController.class).form();
		/* Executando logica de negocio */
		
		User u = dao.editAndSaveUser(user, loginHandler.getUser());
		this.loginHandler.setUser(null);
		this.loginHandler.setUser(u);
		if (u.getEmailValid()==0) {
			this.loginHandler.setUser(null);
		}
		/* Direcionando o resultado */
		this.result.use(Results.logic()).redirectTo(IndexController.class).index();
	}
	@Path("/user/validate/{user.emailValidToken}")
	public User validateToken(User user) {
		User ret = dao.validateEmail(user.getEmailValidToken());
		if (ret ==null) {
			this.result.use(Results.logic()).forwardTo(IndexController.class).index();
		}
		return ret;
	}
}
